import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/event/LoginEvent.dart';
import 'package:panda/event/NumEvent2.dart';
import 'package:panda/event/OfflineEvent.dart';
import 'package:panda/event/UserInfoEvent.dart';
import 'package:panda/home/CatePage.dart';
import 'package:panda/home/MinePage.dart';
import 'package:panda/home/MyShopCar.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/login/UserLogin.dart';
import 'package:panda/login/Welcome.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/SignUtil.dart';

import '../home/MyBottomBar.dart';
import 'HomePage.dart';

class MainPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MainPageWidget();
  }
}

class MainPageWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new MainPageState();
  }
}

class MainPageState extends State<MainPageWidget> with WidgetsBindingObserver {
  int _tabIndex = 0;
  var _pageList = [
    new HomePage(),
    // new CatePage(),
    new MyShopCarPage(),
    new MinePage(),
  ];
  bool isLogin = false;
  int ins = 0;
  String token = "";
  @override
  void initState() {
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      if (!Platform.isIOS)
       if (value == null) {
        // isLogin = true;
        // APPLIC.GG = 1;
        // Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
        //   return new WelComePage();
        // }));
      } else {
        getUserInfo(value);
      }
    });
    APPLIC.eventBus.on<NumEvent2>().listen((event) {
      _tabIndex = event.num;
      setState(() {});
    });
    WidgetsBinding.instance.addObserver(this);
    APPLIC.eventBus.on<LoginEvent>().listen((event) {
      getString(TOKEN).then((value) {
        isLogin = false;
        token = value;
        getUserInfo(value);
      });
    });
    APPLIC.eventBus.on<OfflineEvent>().listen((event) {
      if (APPLIC.GG == 0) {
        APPLIC.GG = 1;
                print('dfdsfasdfsd');

        Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
          return new WelComePage();
        }));
      }
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      if (ModalRoute.of(context).isCurrent)
        getString(TOKEN).then((value) {
          if (value != null) {
            getUserInfo(value);
            // isLogin = true;
            // Navigator.of(context)
            //     .push(new MaterialPageRoute(builder: (context) {
            //   return new WelComePage();
            // }));
          } else {
            // getUserInfo(value);
          }
        });
    }
  }

  getUserInfo(String token) async {
    Map map = new Map();
    map['token'] = token;
    map['sign_type'] = SignType.GET_USERINFO;
    Response<String> response =
        await HttpUtil().post(Api.GET_USERINFO, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      APPLIC.userInfoMap = userMap['data'];
      APPLIC.eventBus.fire(UserInfoEvent(APPLIC.userInfoMap));
    } else {
      isLogin = true;
      // Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
      //   return new WelComePage();
      // }));
    }
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  Widget build(BuildContext context) {
    return new WillPopScope(
        child: Scaffold(
          body: IndexedStack(
            index: _tabIndex,
            children: _pageList,
          ),
          bottomNavigationBar: new MyBottomBar(
            index: _tabIndex,
            onChanged: (index) {
              if (index == 2 || index == 3) {
                if (token == null) {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (context) {
                    return new WelComePage();
                  }));
                  Fluttertoast.showToast(msg: "请先登录");
                  setState(() {
                    _tabIndex = ins;
                  });
                  return;
                }
                // if (index == 3) {
                //   if (APPLIC.userInfoMap['user_msg']['group_id'] < 2) {
                //     Navigator.of(context)
                //         .push(new MaterialPageRoute(builder: (context) {
                //       return new UserUpdateListPage();
                //     }));
                //     Fluttertoast.showToast(msg: "请先成为店长");
                //     APPLIC.eventBus.fire(new NumEvent2(ins));
                //     // setState(() {
                //     //   _tabIndex = ins;
                //     // });
                //     return;
                //   }
                // }
              }
              setState(() {
                ins = index;
                _tabIndex = index;
              });
            },
          ),
        ),
        onWillPop: _onWillPop);
  }

  Future<bool> _onWillPop() {
    return showDialog(
          context: context,
          builder: (context) => new AlertDialog(
            title: new Text('提示'),
            content: new Text('确定退出应用吗？'),
            actions: <Widget>[
              new FlatButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: new Text('再看一会'),
              ),
              new FlatButton(
                onPressed: () => Navigator.of(context).pop(true),
                child: new Text('退出'),
              ),
            ],
          ),
        ) ??
        false;
  }
}
